﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using ScenarioFramework.WorkflowEngine.DataModel.WorkflowProcesses;
using ScenarioFramework.Modules.FormHelper;
using ACEMPortal.Layer.Workflowlayer.DocumentManager;
using ScenarioFramework.Portal;
using System.Drawing;

namespace ScenarioFramework.Portal.SF.Forms.UserControls
{
    public partial class ActivityListAvailable : System.Web.UI.UserControl
    {
        //AllMine = Locked + Unlocked
        public enum ActivityType { Locked, Unlocked, Notifies, AllMine};

        public ActivityType ViewType = ActivityType.Unlocked;

        private FormHelper formHelper = null;

        private void BindActivitiesList(String sSortExpression, bool bAscending)
        {
            ScenarioFramework.WAPI.Response response = new ScenarioFramework.WAPI.Response();
            XMLActivitiesWithAttributes xmlActivities = new XMLActivitiesWithAttributes(Page.User.Identity.Name);
            string sAnswer = string.Empty;

            try
            {
                switch (ViewType)
                {
                    case ActivityType.Locked:
                        sAnswer = WAPI.WorkItem.GetWorkItemListRunningNoNotify(Page.User.Identity.Name, ref response);
                        break;

                    case ActivityType.Unlocked:
                        if (Page.User.IsInRole("SiteAdministrator") ||
                            Page.User.IsInRole("TechnicalManager") ||
                            Page.User.IsInRole("SalesManager"))
                        {
                            sAnswer = ScenarioFramework.WAPI.Activity.GetAllActivityList(Page.User.Identity.Name, ref response);
                        }
                        else
                        {
                            sAnswer = ScenarioFramework.WAPI.Activity.GetActivityList(Page.User.Identity.Name, ref response);
                        }
                        break;

                    case ActivityType.Notifies:
                        sAnswer = WAPI.WorkItem.GetWorkItemListByNotify(Page.User.Identity.Name, ref response);
                        break;

                    case ActivityType.AllMine:
                        sAnswer = ScenarioFramework.WAPI.Activity.GetAllMyActivityList(Page.User.Identity.Name, ref response);
                        break;
                }

                if (response.iCode == 0)
                {
                    xmlActivities.Parse(sAnswer);
                    xmlActivities.Sort(sSortExpression, bAscending);

                    GridAvailable.DataSource = xmlActivities;
                    GridAvailable.DataBind();
                    ViewState["ActivitiesGrid"] = xmlActivities.GetXML(false, 0);
                }
            }
            catch (System.Exception err)
            {
                this.txtDescription.Text = err.Message;
                return;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string sWitchGrid = Request.QueryString["ViewType"];
            switch (sWitchGrid)
            {
                case "Locked":
                    ViewType = ActivityType.Locked;
                    break;
                case "Notifies":
                    ViewType = ActivityType.Notifies;
                    break;
                case "Unlocked":
                    ViewType = ActivityType.Unlocked;
                    break;
                case "AllMine":
                    ViewType = ActivityType.AllMine;
                    break;
            }
            if (!Page.IsPostBack)
            {
                formHelper = Global.FormsHelper.GetFormHelper();
                Session["FormHelper"] = formHelper;

                BindActivitiesList(String.Empty, false);
            }
            else
            {
                formHelper = (FormHelper)Session["FormHelper"];
            }
        }

        private XMLActivityWithAttributes GetXMLActivityFromGridRow(string sViewStateKey, int iItemIndex)
        {
            //TODO: inserisci controlli e lancio eccezioni...Parsing di tutte le activity..
            XMLActivitiesWithAttributes xmlActivities = new XMLActivitiesWithAttributes(Page.User.Identity.Name);
            xmlActivities.Parse((string)ViewState[sViewStateKey]);
            return (XMLActivityWithAttributes)xmlActivities[iItemIndex];

        }

        protected void GridAvailable_EditCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                XMLActivityWithAttributes xmlActivity = GetXMLActivityFromGridRow("XMLActivitiesToDo", e.Item.ItemIndex);
                txtDescription.Text = xmlActivity.Description;

                if (xmlActivity.HelpUrl != string.Empty)
                {
                    txtDescription.Text += " <a href=\"" + Page.ResolveUrl(xmlActivity.HelpUrl) + "\" class=\"MoreInfo\" target=\"_blank\">MoreInfo</a>.";
                }
            }
            catch
            {
            }
        }

        protected void GridAvailable_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            XMLActivityWithAttributes xmlActivity = null;

            try
            {
                xmlActivity = GetXMLActivityFromGridRow("XMLActivitiesToDo", e.Item.ItemIndex);

                if (xmlActivity.XMLLog.Status == XMLLog.RUNNING_STATUS)
                {

                    txtDescription.Text = xmlActivity.ActivityAlias + " already Running!";
                    txtDescription.ForeColor = Color.Black;
                    return;

                }
            }
            catch
            {
                txtDescription.Text = "NO ACTIVITY FOUND IN COLLECTION  !!!!!!!!!!";
                txtDescription.ForeColor = Color.Red;
            }

            string ActionName = "ToDo.DoActivity." + xmlActivity.Name;
            string ActivityParams = ".aspx?GridType=Available&IdProcess=" + xmlActivity.ProcessId + "&IdActivity=" + xmlActivity.Name;
            //string Path = "../PCMForms/Forms/";
            string Path = "";

            string strAnsware = formHelper.ExecuteAction(Page.User.Identity.Name, ActionName, xmlActivity.ProcessId.ToString(), xmlActivity.Name);
            if (strAnsware == "KO")
            {
                txtDescription.Text = "Impossible to acquire Activity[" + xmlActivity.ActivityAlias + "]. Refresh Activities List to chek if it 's available too.";
                txtDescription.BackColor = Color.Yellow;
                return;
            }
            else if (strAnsware == "NO ACTION ALLOWED")
            {
                ActionName = "ToDo.DoActivity.Generic";
                strAnsware = formHelper.ExecuteAction(Page.User.Identity.Name, ActionName, xmlActivity.ProcessId.ToString(), xmlActivity.Name);
            }

            if (strAnsware != null && strAnsware.Length > 0 && strAnsware != "OK" && strAnsware != "NO ACTION ALLOWED")
            {
                Response.Redirect(Path + strAnsware + ActivityParams);
            }
        }

        protected void GridAvailable_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            /*if (e.Item.DataItem != null)
			{
				XMLActivityWithAttributes activity = (XMLActivityWithAttributes)e.Item.DataItem;
				e.Item.Cells[0].Attributes.Add("onmouseover", "ShowTooltip('" + activity.Description + 
					//DataBinder.Eval(e.Item.DataItem, "client_name").ToString() + "','" + 
					//DataBinder.Eval(e.Item.DataItem, "Address").ToString() + "','" + 
					//DataBinder.Eval(e.Item.DataItem, "CITY").ToString() + "','" + 
					//DataBinder.Eval(e.Item.DataItem, "STATE").ToString() + "', '" + 
					//DataBinder.Eval(e.Item.DataItem, "PHONE1").ToString() + "','" + 
					//DataBinder.Eval(e.Item.DataItem, "FAX").ToString() + 
					"');"); 
				e.Item.Cells[0].Attributes.Add("onmouseout","HideTooltip();");
			}
			*/
        }

        protected void GridAvailable_SortCommand(object source, DataGridSortCommandEventArgs e)
        {
            object obj = ViewState["SortExpression"];
            if (obj == null)
            {
                this.BindActivitiesList(e.SortExpression, true);
            }
            else
            {
                String sOldSortExpression = (string)obj;
                if (sOldSortExpression.CompareTo(e.SortExpression) == 0)
                {
                    this.BindActivitiesList(e.SortExpression, false);
                }
                else
                {
                    this.BindActivitiesList(e.SortExpression, true);
                }
            }
            ViewState["SortExpression"] = e.SortExpression;
        }
    }
}